package com.itheima.controller;

import com.github.pagehelper.Page;
import com.itheima.common.exception.ExceptionCast;
import com.itheima.common.response.PageResult;
import com.itheima.common.response.ResponseResult;
import com.itheima.common.response.StatusCode;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Dqh
 * @create 2020-09-18 19:10
 * @desc 用户的表现层
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * @desc:  查询所有用户的方法
    * @param
     * @return:
     * @author: Dqh  2020/9/18  19:12
     */
    @GetMapping("/findAll")
    public ResponseResult<User> findAll(){
        List<User> user = userService.findAll();
        return ResponseResult.okResult(user);
    }

    /**
     * @desc: 新增用户
    * @param user
     * @return:
     * @author: Dqh  2020/9/18  19:49
     */
    @PostMapping("/addUser")
    public ResponseResult<User> addUser(@RequestBody User user){
        return ResponseResult.okResult(userService.addUser(user));
    }

    /**
     * @desc:  根据uuid删除用户
    * @param uuid
     * @return:
     * @author: Dqh  2020/9/18  19:59
     */
    @PostMapping("/deleteUser")
    public ResponseResult<User> deleteUser(@RequestParam Integer uuid){
        return ResponseResult.okResult(userService.deleteUser(uuid));
    }

    /**
     * @desc: 根据uuid查找用户
    * @param uuid
     * @return:
     * @author: Dqh  2020/9/18  20:14
     */
    @PostMapping("/findOne")
    public ResponseResult<User> findOne(@RequestParam Integer uuid){
        User user = userService.findOne(uuid);
        return new ResponseResult<User>(user!=null ? StatusCode.SUCCESS.getCode() : StatusCode.ERROR.getCode(),
                user!=null ? "查询成功" : "查询失败", user);
    }

    /**
     * @desc:  更新用户
    * @param user
     * @return:
     * @author: Dqh  2020/9/18  20:15
     */
    @PostMapping("/update")
    public ResponseResult<User> update(@RequestBody User user){
        boolean b = userService.update(user);
        return new ResponseResult<User>(b!=true ? StatusCode.SUCCESS.getCode() : StatusCode.ERROR.getCode(),
                user!=null ? "修改成功" : "修改失败", user);
    }

    @PostMapping("/search/{page}/{size}")
    public ResponseResult<PageResult> search(@RequestBody User user, 	@PathVariable("page") Integer page,
                                       @PathVariable("size") Integer size){
        Page<User> pages = userService.search(user,page, size);
        // 数据列表，总记录，总页数
        PageResult pageResult =
                new PageResult(pages.getTotal(),pages.getPages(),pages.getResult());
        return new ResponseResult<PageResult>(StatusCode.SUCCESS.getCode(), "查询成功", pageResult);
    }

}
